<?php
/**
 * 
 * 会员中心 
 * @author wj 
 * @date  2014-10-13
 *
 */
class TradeController extends BaseController {
    public function _initialize() {
        parent::_initialize();
        $this->db = model('Order');
        $this->order_goods_db = model('OrderGoods');
        $this->id = session('id');
    }
   
    // 交易中心
    public function index()
    {
        $type = $_GET['type'];
        $sqlmap = array();
        if(isset($_GET['keyword']) && $_GET['keyword']){
            $map['username|real_name'] = array('like',"%".trim($_GET['keyword'])."%");
            $ids = M('user')->where($map)->getField('id',true);
            $sqlmap['u.id'] = array('in',$ids);
        }
        // var_dump($sqlmap);
        if($type == 'buy'){
            
            //求购列表
            $list = M('hang_buy h')
                    ->where(['h.status'=>1,'h.user_id'=>['neq',session('id')]])
                    ->join('__USER__ u on h.user_id=u.id')
                    ->where($sqlmap)
                    ->field('u.real_name,u.username,u.photo,h.add_time,h.number,h.need_pay as all_price,h.user_id,h.id')
                    ->select();
            foreach($list as $key => $value){
                
                $list[$key]['num'] = M('hang_buy')->where(['user_id'=>$value['user_id'],'status'=>4])->count();//出售数量
               
                $good_evaluate  = M('hang_buy')->where(['user_id'=>$value['user_id'],'status'=>4,'buyer_evaluate'=>1])->count();
                
                $list[$key]['good_evaluate_percent'] = $list[$key]['num'] == 0 ? 0 : round($good_evaluate/$list[$key]['num']*100,2);//好评率
               
            }
        }else{
            //出售列表
            // echo $type;
            $list = M('hang_sell h')
                    ->where(['h.status'=>1,'h.user_id'=>['neq',session('id')],'h.left_number'=>['gt',0]])
                    ->join('__USER__ u on h.user_id=u.id')
                    ->where($sqlmap)
                    ->field('u.real_name,u.username,u.photo,h.add_time,h.left_number as number,h.left_price as all_price,h.user_id,h.id')
                    ->select();
            foreach($list as $key =>$value){
          
                $list[$key]['num'] = M('hang_buy')->where(['sell_id'=>$value['user_id'],'status'=>4])->count();//出售数量
             
                $good_evaluate  = M('hang_buy')->where(['sell_id'=>$value['user_id'],'status'=>4,'seller_evaluate'=>1])->count();
          
                $list[$key]['good_evaluate_percent'] = $list[$key]['num'] == 0 ? 0 : round($good_evaluate/$list[$key]['num']*100,2);//好评率
       
            }
        }
        
        $userInfo = M('user')->where(['id'=>session('id')])->field('upvaluation')->find();
        $info = M('wallet_price')->where(['start_time'=>['in',[mktime(0,0,0,date('m'),date('d'),date('Y')),mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1]]])->find();
       
        $records  = M('upvaluation_put_records up')->where(['up.if_reward'=>array('neq',1)])->join('__USER__ u on u.id=up.user_id')->field('u.username,up.*')->select();
        
        
        $sqlmap1 = array();
        // $start_time = NOW_TIME - 86400 * 4;
        $timeb = NOW_TIME;
        $days = 5;
        $wallet = model('WalletPrice');
        for ($i=0; $i < $days; $i++) {
            $_time = $timeb - 86400 * $i;
            $_day = mdate($_time, 'Y-m-d');
            $sqlmap1['_string'] = "DATE_FORMAT(FROM_UNIXTIME(time),'%Y-%m-%d') = '".$_day."'";
            $walletLists[mdate($_time, 'm-d')] = (float) $wallet->where($sqlmap1)->getField('price');
        }
        $walletLists = array_reverse($walletLists, TRUE);
        $sell_days  = array_keys($walletLists);
        $series[]   = array('name' =>'DBT价格', 'data' => array_values($walletLists),'color'=>'#1b8ca5');
        include template('/user/trade/index');
    }
    
    //处理交易 买入卖出
    public function deal_trade()
    {   
        //type 1：没有实名 2： 不在交易时间内 3： 保证金不足 4： 买入价格低于最低价格
        $start_time = C('site_timea');
        $end_time = C('site_timeb');
        if(IS_POST){
            $id = session('id');
            $param = I('post.');
            if($param['type'] == 'buy'){
                //说明是买入
                $info = M('user')->where(['id'=>$id,'if_identification'=>3])->field('id,username,real_name,balance')->find();
                if(!$info) showmessage('您还没有实名认证');
                $time = date('H');
                if($time < $start_time || $time > $end_time) showmessage("交易时间为每天的".$start_time."点到".$end_time."点");
                if($info['balance'] <= 100)  showmessage('您的保证金不足100');
                $price_info = M('wallet_price')->where(['start_time'=>['in',[mktime(0,0,0,date('m'),date('d'),date('Y')),mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1]]])->find();
                if($param['price'] < $price_info['price']) showmessage('买入价格不能低于最低价格');
                $all_upvaluation = $param['num']*$param['price'];
                $data = [
                    'user_id'=>$id,
                    'number'=>$param['num'],
                    'price'=>$param['price'],
                    'all_price'=>$all_upvaluation,
                    'need_pay'=>$all_upvaluation,
                    'order_number'=>$id.time(),//先制空
                    'status'=>1,
                    'add_time'=>date('Y-m-d H:i:s'),
                    'update_time'=>date('Y-m-d H:i:s')
                ];
                try{

                    // $config = (int)C('site_trate_fee');
                    // var_dump($config);die;
                    $percent = (1-C('site_trate_fee')/100);
                    // var_dump($percent);
                    // die;
                    M()->startTrans();
                    M('hang_buy')->add($data);
                    $change = [
                        'balance'=>$info['balance']-100,
                        'freeze_balance' => $info['freeze_balance'] + 100
                    ];
                    M('user')->where(['id'=>$id])->save($change);
                    $data1 = [
                        'user_id'=>$id,
                        'balance'=>-100,
                        'type'=>3,
                        'remarks'=>'购买GF扣除保证金',
                        'add_time'=>date('Y-m-d H:i:s')
                    ];
                    M('balance_exchange_records')->add($data1);
                    M()->commit();
                }catch(\Exception $e){
                    M()->rollback();
                    showmessage($e->getMessage());
                }
                showmessage('请等待卖家匹配','goback',1);
            }else{
                //说明是出售
                $info = M('user')->where(['id'=>$id,'if_identification'=>3])->field('id,username,real_name,balance,upvaluation,freeze_upvaluation,freeze_balance')->find();
                if(!$info) showmessage('您还没有实名认证');
                $time = date('H');
                if($time < $start_time || $time > $end_time) showmessage("交易时间为每天的".$start_time."点到".$end_time."点");
                $price_info = M('wallet_price')->where(['start_time'=>['in',[mktime(0,0,0,date('m'),date('d'),date('Y')),mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1]]])->find();
                if($param['price'] < $price_info['price']) showmessage('卖出价格不能低于最低价格');
                if($info['balance'] < 100) showmessage('您的交易保证金不足');
                
                $all_upvaluation = $param['num']*$param['price'];
                $data = [
                    'user_id'=>$id,
                    'number'=>$param['num'],
                    'left_number'=>$param['num'],
                    'price'=>$param['price'],
                    'left_price'=>$all_upvaluation,//可卖出的人民币
                    'status'=>1,
                    'add_time'=>date('Y-m-d H:i:s'),
                    'update_time'=>date('Y-m-d H:i:s'),
                    'charge_percent'=>C('site_trate_fee'),
                ];
                try{
                    // $config = (int)C('site_trade_percent');
                    // var_dump($config);die;
                    // $percent = (1-C('site_trate_fee')/100);
                    $percent = C('site_trate_fee')/100;
                    // var_dump($percent);
                    // die;
                    
                    M()->startTrans();
                   
                    //判定是否是系统运行一个月内
                    // $system_time = M('system_time')->where(['id'=>1])->find()['system_time'];
                    // $after_one_month_time = 11;
                    // $freeze = ($after_one_month_time > time()) ? $param['num']*(1+$percent) : $all_upvaluation = $param['num']*$param['price']; 
                    $freeze = $param['num']*(1+$percent);
                    M('hang_sell')->add($data);
                    $change = [
                        'upvaluation'=>$info['upvaluation']-$freeze,
                        'freeze_upvaluation' => $info['freeze_upvaluation'] + $freeze,
                        'balance'=>$info['balance'] -100,
                        'freeze_balance'=>$info['freeze_balance'] + 100,
                        
                    ];
                    $data1 = [
                        'user_id'=>$this->id,
                        'balance'=>-$freeze,
                        'type'=>3,
                        'add_time'=>date('Y-m-d H:i:s'),
                        'remarks'=>'交易GF扣除'
                    ];
                    $data2 = [
                        'user_id'=>$this->id,
                        'balance'=>-100,
                        'type'=>3,
                        'add_time'=>date('Y-m-d H:i:s'),
                        'remarks'=>'出售GF扣除保证金'
                    ];
                    M('balance_exchange_records')->add($data2);
                    M('user')->where(['id'=>$id])->save($change);
                    M('upvaluation_exchange_records')->add($data1);
                    M()->commit();
                }catch(\Exception $e){
                    M()->rollback();
                    showmessage($e->getMessage());
                }
                showmessage('请等待买家购买','goback',1);
            }
        }else{
            showmessage('非法访问');
        }
    }




    //列表出售，购买
    public function list_trade()
    {
        if(IS_POST){
            $type = $_POST['type'];
            $id = $_POST['id'];
            // var_dump($id);die;
            $user_id = session('id');
            if($type == 'sell'){
                //说明是买入      
                // echo 1;
                $user_info = M('user')->where(['id'=>$user_id])->find();
                if($user_info['if_identification'] != 3) showmessage('您还没有实名认证');
                if($user_info['balance'] < 100) showmessage('您的交易保证金不足100');
                $sell_info = M('hang_sell')->where(['id'=>$id])->find();
              
                try{
                    M()->startTrans();
                    $change = [
                        'balance'=>$user_info['balance'] - 100,
                        'freeze_balance'=>$user_info['freeze_balance'] + 100,
                    ];
                    $all_price = $info['left_number']*$info['price'];
                    $data = [
                        'hang_sell_id'=>$id,
                        'user_id'=>$user_id,
                        'sell_id'=>$sell_info['user_id'],
                        'number'=>$sell_info['left_number'],
                        'price'=>$sell_info['price'],
                        'all_price'=>$all_price,
                        'need_pay'=>$all_price*C('site_exchange_bili'),
                        'charge_percent'=>$sell_info['charge_percent'],
                        'order_number'=>$user_id.time(),
                        'status'=>2,
                        'add_time'=>date('Y-m-d H:i:s'),
                        'update_time'=>date('Y-m-d H:i:s')
                    ];
                    // var_dump($data);die;
                    $data1 = [
                        'left_number'=>0,
                        'left_price'=>0,
                        'status'=>2,
                        'update_time'=>date('Y-m-d H:i:s')
                    ];
                    $data2 = [
                        'user_id'=>$this->id,
                        'balance'=>-100,
                        'type'=>3,
                        'remarks'=>'购买GF扣除交易保证金',
                        'add_time'=>date('Y-m-d H:i:s')
                    ];
                    M('balance_exchange_records')->add($data2);
                    M('user')->where(['id'=>$user_id])->save($change);
                    M('hang_buy')->add($data);
                    M('hang_sell')->where(['id'=>$id])->save($data1);
                    M()->commit();
                }catch(\Exception $e){
                    M()->rollback();
                    showmessage($e->getMessage());
                }
                showmessage('操作成功,请于3小时之内付款','goback',1);
            }else{
                // echo 2;
                //说明出售
                $user_info = M('user')->where(['id'=>$user_id])->find();
                if($user_info['if_identification'] != 3) showmessage('您还没有实名认证');
                $info = M('hang_buy')->where(['id'=>$id])->field('number,price,all_price,need_pay')->find();

                //判定是否是系统运行一个月内
                // $system_time = M('system_time')->where(['id'=>1])->find()['system_time'];
                // $after_one_month_time = 11;
                // $freeze = ($after_one_month_time > time()) ? $param['num']*(1+$percent) : $all_upvaluation = $param['num']*$param['price']; 
                   

                $trade_percent = C('site_trade_percent');
                $need_have = $info ['number']*(1+$trade_percent/100);
                if($need_have > $user_info['upvaluation']) showmessage('您的升值链不足'.$need_have);
                try{
                    M()->startTrans();
                    $change = [
                        'upvaluation' => $user_info['upvaluation'] - $need_have,
                        'freeze_upvaluation'=> $user_info['freeze_upvaluation'] + $need_have,
                     ];
                    $data = [
                        'sell_id'=>$user_id,
                        'need_pay'=>$info['all_price']*C('site_exchange_bili'),
                        'charge_percent'=>$trade_percent,
                        'status'=>2,
                        'update_time'=>date('Y-m-d H:i:s')
                    ];
                    M('user')->where(['id'=>$user_id])->save($change);
                    M('hang_buy')->where(['id'=>$id])->save($data);


                     

                    $data1 = [
                        'user_id'=>$this->id,
                        'balance'=>-$freeze,
                        'type'=>3,
                        'add_time'=>date('Y-m-d H:i:s'),
                        'remarks'=>'交易扣除GF'
                    ];
                    M('upvaluation_exchange_records')->add($data1);
                    $data2 = [
                        'user_id'=>$this->id,
                        'balance'=>-100,
                        'type'=>3,
                        'add_time'=>date('Y-m-d H:i:s'),
                        'remarks'=>'出售GF扣除交易保证金'
                    ];
                    M('balance_exchange_records')->add($data2);
                    M()->commit();
                }catch(\Exception $e){
                    M()->rollback();
                    showmessage($e->getMessage());
                }
                showmessage('卖出成功,请等待买家付款','goback',1);
               
            }
        }else{
            shomessage('非法访问');
        }
    }




    /**
     * 取消交易
     * 必须是在状态为status=1 才可以取消
     */
    public function cancel(){
        $id = I("id",0,"intval");
        $info = M("user_trade")->find($id);
        if($info['user_id']!=$this->userinfo['id'])  showmessage('参数错误！');
        if($info['status']!=1) showmessage('交易无法取消');

        $rut = M("user_trade")->where("id=".$id)->setField("status",0);
        if($rut){
            showmessage('操作成功！',"",1);
        }else{
            showmessage('操作失败！',"",1);
        }
    }








    // 操作 买入 卖出
   
    // 交易中心 购买
    
    // 交易中心 出售
   
    // 交易详情
    
    // 上传截图 交易凭证
    public function picadd(){
        $id= I("id",0,"intval");
        if($id==0) showmessage("参数错误！");
        $pic = I("pic","","htmlspecialchars");
        if($pic=="") showmessage("请上传截图！");
        $tinfo = M("user_trade")->find($id);
        if($tinfo['pic']==='') showmessage("请勿重复上传！");
        $data = array();
        $data['id'] = $tinfo['id'];
        $data['pic'] = $pic;
        $data['order_status'] = 2;//待确认
        $data['pic_time'] = NOW_TIME;
        $rut = M("user_trade")->save($data);
        if($rut){
            showmessage("操作成功！","",1);
        }else{
            showmessage("操作失败！");
        }
    }
    // 投诉
    public function complainadd(){
        $id= I("id",0,"intval");
        if($id==0) showmessage("参数错误！");
        $complain = I("complain","","htmlspecialchars");
        if($complain=="") showmessage("请填写投诉内容");
        $tinfo = M("user_trade")->find($id);
        // if($tinfo['pic']!=="") showmessage("请勿重复上传！");
        $data = array();
        $data['user_id'] = $this->userinfo["id"];
        $data['order_id'] = $tinfo['id'];
        $data['content'] = $complain;
        if($tinfo['user_id']==$this->userinfo["id"]){
            $data['to_uid'] = $tinfo['sell_id'];
        }else{
            $data['to_uid'] = $tinfo['user_id'];
        }
        $data['dateline'] = NOW_TIME;
        $rut = M("complain")->add($data);
        // echo M()->getlastsql();
        if($rut){
            showmessage("操作成功！","",1);
        }else{
            showmessage("操作失败！");
        }
    }
    // 确认收款
    public function confirmorder(){
        $id= I("id",0,"intval");
        if($id==0) showmessage("参数错误！");
        $tinfo = M("user_trade")->find($id);
        if($tinfo['order_status']!=2) showmessage("参数错误！");
        $buyer = M("user")->find($tinfo['user_id']);
        $seller = M("user")->find($tinfo['sell_id']);
        M()->startTrans();
        // 卖家冻结的金额扣除 sell_num
        $rut = M("user")->where("id=".$tinfo['sell_id'])->setDec("freeze_money",$tinfo['sell_num']);
        // 资金变动记录 减交易余额
        $moneylog = array();
        $moneylog['user_id'] = $tinfo['sell_id'];
        $moneylog['money'] = -$tinfo['num'];
        $moneylog['msg'] = "出售:{$tinfo[num]}DBT";
        $moneylog['type'] = 4;
        $moneylog['user_money'] = $seller['user_money'];
        $moneylog['freeze_money'] = $seller['freeze_money']-$tinfo['num'];
        $moneylog['dateline'] = NOW_TIME;
        $rut1 = M("user_moneylog")->add($moneylog);
        // 资金变动记录 减交易手续费
        $moneylog = array();
        $moneylog['user_id'] = $tinfo['sell_id'];
        $moneylog['money'] = -$tinfo['sell_fee'];
        $moneylog['msg'] = "手续费:{$tinfo[sell_fee]}DBT";
        $moneylog['type'] = 14;
        $moneylog['user_money'] = $seller['user_money'];
        $moneylog['freeze_money'] = $seller['freeze_money']-$tinfo['sell_num'];
        $moneylog['dateline'] = NOW_TIME;
        $rut1 = M("user_moneylog")->add($moneylog);
        // echo M()->getlastsql();
        // 买家增加购买金额 num
        $rut2 = M("user")->where("id=".$tinfo['user_id'])->setInc("user_money",$tinfo['num']);
        // 资金变动记录 减余额
        $moneylog = array();
        $moneylog['user_id'] = $tinfo['user_id'];
        $moneylog['money'] = $tinfo['num'];
        $moneylog['msg'] = "买入";
        $moneylog['type'] = 5;
        $moneylog['user_money'] = $buyer['user_money']+$tinfo['num'];
        $moneylog['freeze_money'] = $buyer['freeze_money'];
        $moneylog['dateline'] = NOW_TIME;
        $rut3 = M("user_moneylog")->add($moneylog);
        $rut4 = M("user_trade")->where("id=".$tinfo['id'])->save(array(
            'status'=>3,
            'order_status'=>3,
            'confi_time'=>NOW_TIME
        ));
        // var_dump($rut);
        // var_dump($rut1);
        // var_dump($rut2);
        // var_dump($rut3);
        // var_dump($rut4);
        if($rut!==false && $rut1!==false && $rut2!==false && $rut3!==false && $rut4!==false){
            M()->commit();
            showmessage("操作成功！","",1);
        }else{
            M()->rollback();
            showmessage("操作失败！");
        }
    }
    public function evaluate(){
        $id= I("id",0,"intval");
        if($id==0) showmessage("参数错误！");
        $evaluate = I("evaluate",0,"intval");
        if($evaluate==0) showmessage("参数错误！");
        $tinfo = M("user_trade")->find($id);
        // if($tinfo['pic']!=="") showmessage("请勿重复上传！");
        if($tinfo['order_status']!=3) showmessage("操作失败！");
        if($tinfo['sell_id']!==$this->userinfo['id'] && $tinfo['user_id']!==$this->userinfo['id'])  showmessage("操作失败！");
        // 如果是卖家  则评价给买家
        if($tinfo['sell_id']==$this->userinfo['id']){
            if($tinfo['buyer_evaluate']>0)  showmessage("已经评价过了！");
            $rut = M("user_trade")->where("id=".$tinfo['id'])->setField("buyer_evaluate",$evaluate);
        }
        // 如果是买家  则评价给卖家
        if($tinfo['user_id']==$this->userinfo['id']){
            if($tinfo['seller_evaluate']>0)  showmessage("已经评价过了！");
            $rut = M("user_trade")->where("id=".$tinfo['id'])->setField("seller_evaluate",$evaluate);
        }
        if($rut){
            showmessage("操作成功！","",1);
        }else{
            showmessage("操作失败！");
        }   
    }
    // // 会员中心 交易列表
    // public function tradelog(){
    //     $SEO = seo(0,"交易列表");
    //     include template('/user/trade/tradelog');
    // }
   
    }